//
//  JKViewFriendsSegment.m
//  chequanbao_ios
//
//  Created by 朱凯 on 2018/1/24.
//  Copyright © 2018年 com.itboye. All rights reserved.
//

#import "JKViewFriendsSegment.h"



@implementation JKViewFriendsSegment
{
    UIColor *_color;
}
- (instancetype)init {
    
    if (self = [super init]) {
    
        self.backgroundColor = TABLE_COLOR;
        _color = rgba(118, 197, 250, 1);
    }
    return self;
}
- (void)setSegments:(NSArray *)segments {
    
    _segments = segments;
    
    [self setupUI];
}
- (void)setupUI {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIView *bgView = [UIView new];
    bgView.tag = 100;
    [self addSubview:bgView];
    bgView.layer.borderColor = _color.CGColor;
    bgView.layer.borderWidth = 1;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@10);
        make.right.bottom.equalTo(@-10);
    }];
    
    UIButton *last = nil;
    for (int i = 0; i < _segments.count; i ++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = FONT(15);

        [button setTitle:_segments[i] forState:UIControlStateNormal];
        [button setTitleColor:_color forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:_color] forState:UIControlStateSelected];
        [button addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:button];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(bgView).multipliedBy(1.0 / _segments.count);
            make.top.bottom.equalTo(@0);
            if (last) {
                make.left.equalTo(last.mas_right);
            } else {
                make.left.equalTo(@0);
            }
        }];
        
        last = button;
        
        if (i == 0) {
            button.selected = true;
        }
    }
}

- (void)tapAction:(UIButton *)button {
    
    if (button.selected) {
        return;
    }
   
    UIView *bgView = [self viewWithTag:100];
    
    [bgView.subviews enumerateObjectsUsingBlock:^(__kindof UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj == button) {
            obj.selected = true;
            if (self.selectBlock) {
                self.selectBlock(idx);
            }
        } else {
            obj.selected = false;
        }
    }];
}

@end
